<template>
  <section class="f-inventory">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">库存列表</span>
        <div style="margin-left:auto;">
          <el-button type="primary" plain @click="off.dialogVisible = true">调拨</el-button>
          <el-button type="info" plain @click="importHandle(1)">导入</el-button>
          <el-button type="warning" plain @click="exportHandle()">导出</el-button>
        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>设备商品ID：</span>
          <el-input v-model="searchForm.wareGoodsId" clearable placeholder="请输入设备商品ID" />
        </div>
        <div>
          <span>设备型号：</span>
          <el-input v-model="searchForm.equipmentType" clearable placeholder="请输入设备型号" />
        </div>
        <div>
          <span>设备颜色：</span>
          <el-input v-model="searchForm.color" clearable placeholder="请输入设备颜色" />
        </div>
        <div>
          <span>ICCID：</span>
          <el-input v-model="searchForm.iccid" clearable placeholder="请输入ICCID" />
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="selectionChange">
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="wareGoodsId" label="设备商品ID" align="center">
            <template v-slot="scope">
              <el-link style="font-size:12px" type="primary" @click="lookDetail(scope.row)">
                {{ scope.row.wareGoodsId || '' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="equipmentType" label="设备型号" align="center">
            <template v-slot="scope">
              {{ scope.row.equipmentType || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="color" label="设备颜色" align="center">
            <template v-slot="scope">
              {{ scope.row.color || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="totalIn" label="总入库" align="center">
            <template v-slot="scope">
              {{ scope.row.totalIn  }}
            </template>
          </el-table-column>
          <el-table-column prop="rest" label="可用余量" align="center">
            <template v-slot="scope">
              {{ scope.row.rest }}
            </template>
          </el-table-column>
          <el-table-column prop="totalDistributeToCompany" label="已调拨" align="center">
            <template v-slot="scope">
              {{ scope.row.totalDistributeToCompany }}
            </template>
          </el-table-column>
          <el-table-column prop="totalDistributeToCompanyPre" label="待调拨" align="center">
            <template v-slot="scope">
              {{ scope.row.totalDistributeToCompanyPre  }}
            </template>
          </el-table-column>
          <el-table-column prop="createTimeMill" label="创建时间" align="center">
            <template v-slot="scope">
              {{ getDateTime(scope.row.createTimeMill)[6] || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template v-slot="scope">
              <div class="table-handle-box">
                <el-link style="font-size:12px" type="primary" @click="exportWarehouseImportTemplate(scope.row)">下载模板</el-link>
                <el-link style="font-size:12px" type="primary" @click="importHandle(3)">回拨</el-link>
                <el-link style="font-size:12px" type="danger" @click="importHandle(2)">退库</el-link>
                <!-- <el-link style="font-size:12px" type="danger" @click="settingHandle(1,scope.row)">删除</el-link> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <!-- <div class="footer_btn_box">
            <el-button :disabled="chooseList.length == 0" @click="settingHandle" type="danger" plain size="small">批量删除</el-button>
          </div> -->
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" :apiName="apiName" @handleUploadSuccess="importSuccess"
      @handleUploadCancel="handleUploadCancel">
      <template #slotForm="parent">
        <section v-if="uploadType == 2">
          <el-form-item prop="businessTime" label="操作时间" label-width="100">
            <el-date-picker v-model="parent.formData.data.businessTime" type="datetime" value-format="x" placeholder="请选择日期时间" />
          </el-form-item>
          <el-form-item prop="remarks" label="备注" label-width="100">
            <el-input v-model="parent.formData.data.remarks" :rows="3" type="textarea" placeholder="请输入备注..." />
          </el-form-item>
        </section>
        <section v-if="uploadType == 3">
          <el-form-item prop="fromShopId" label="来源代理商" label-width="100">
            <el-select v-model="parent.formData.data.fromShopId" filterable placeholder="请选择" style="width: 250px;">
              <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
            </el-select>
          </el-form-item>
          <el-form-item prop="toShopId" label="目标代理商" label-width="100">
            <el-select v-model="parent.formData.data.toShopId" filterable placeholder="请选择" style="width: 250px;">
              <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
            </el-select>
          </el-form-item>
          <el-form-item prop="businessTime" label="操作时间" label-width="100">
            <el-date-picker v-model="parent.formData.data.businessTime" type="datetime" value-format="x" placeholder="请选择日期时间"
              style="width: 250px !important" />
          </el-form-item>
          <el-form-item prop="remarks" label="备注" label-width="100">
            <el-input v-model="parent.formData.data.remarks" :rows="3" type="textarea" placeholder="请输入备注..." />
          </el-form-item>
        </section>
      </template>
    </Upload>

    <!-- 确认密码 -->
    <ConfirmPass ref="confirmPasswordRef" @verification="confirmSuccess" />

    <!-- 调拨弹窗 -->
    <el-dialog v-model="off.dialogVisible" title="设备调拨" width="600">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="shopId" label="代理商">
          <el-select v-model="dialogForm.shopId" filterable placeholder="请选择">
            <el-option v-for="item in shopList1" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="orderId" label="订单号">
          <el-input v-model="dialogForm.orderId" clearable placeholder="请输入订单号" />
        </el-form-item>
        <section class="f-strategy-box">
          <el-scrollbar max-height="400px">
            <div class="f-strategy-header">
              <p>设备商品列表</p>
              <el-button class="f-ml-20" type="warning" size="small" plain @click="strategyAdd('deviceList',1)">
                + 添加
              </el-button>
            </div>
            <ul class="f-strategy-body">
              <li v-for="(item,index) in deviceList" :key="index">
                <p>设备商品ID：</p>
                <el-select v-model="item.wareGoodsId" filterable clearable placeholder="请选择" style="width: 150px;">
                  <el-option v-for="myItem in warehouseChooseList" :key="myItem.wareGoodsId" :label="myItem.wareGoodsId"
                    :value="myItem.wareGoodsId" />
                </el-select>

                <p class="f-ml-20">调拨数量：</p>
                <el-input-number v-model="item.num" :min="1" controls-position="right" style="width: 120px;" placeholder="请输入" />

                <el-button class="f-ml-20" type="danger" plain @click="strategyDelete('deviceList',index)">
                  - 删除
                </el-button>

                <p class="f-divider f-mt-20" v-if="deviceList.length > index + 1"></p>
              </li>
            </ul>

          </el-scrollbar>
        </section>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel()">取消</el-button>
          <el-button type="primary" @click="dialogSave()">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import Upload from '@/components/Upload.vue'
import ConfirmPass from '@/components/confirmPass.vue'
import api from '../api'
import { Search } from 'vant'
export default {
  components: { Upload, ConfirmPass },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)
    const confirmPasswordRef = ref(null)
    const dialogFormRef = ref(null)

    const state = reactive({
      off: {
        upload: false,
        dialogVisible: false,
      },
      isDetail: false,

      searchForm: {
        "color": "",
        "equipmentType": "",
        "orderBy": "id desc",
        "wareGoodsId": ""
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      uniqueId: '',
      chooseList: [],

      apiName: 'warehouseImportTemplate',
      uploadForm: {
        dialogTitle: '导入库存',
        action: '/eas/manage/yilian/warehouse/importData'
      },

      shopList: [],
      shopList1: [],
      warehouseChooseList: [],
      uploadType: 1,
      dialogForm: {},
      dialogRules: {
        shopId: [
          { required: true, message: "请选择代理商", trigger: "change" },
        ],
      },
      deviceList: [{}]
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/inventoryGoods')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "color": "",
        "equipmentType": "",
        "orderBy": "id desc",
        "wareGoodsId": ""
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
      }
      api.warehouseList(obj).then(res => {
        state.tableData = res.data.list
        state.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(data) {
      router.push({
        path: '/inventoryGoodsDetail',
        query: {
          wareGoodsId: data.wareGoodsId,
          equipmentType: data.equipmentType,
          color: data.color,
          iccid: state.searchForm.iccid
        }
      })
    }

    // 导出
    const exportHandle = () => {
      const obj = {
        responseType: 'blob',
        ...state.searchForm,
      }
      api.warehouseListDown(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    // 导入
    function importHandle(type) {
      state.uploadType = type
      if (type == 1) {
        state.apiName = 'warehouseImportTemplate'
        state.uploadForm = {
          dialogTitle: '导入库存',
          action: '/eas/manage/yilian/warehouse/importData'
        }
      } else if (type == 2) {
        state.apiName = 'tuikuImportTemplate'
        state.uploadForm = {
          dialogTitle: '导入退库',
          action: '/eas/manage/yilian/tuiku/importData'
        }
      } else if (type == 3) {
        state.apiName = 'shouhuiImportTemplate'
        state.uploadForm = {
          dialogTitle: '导入回拨',
          action: '/eas/manage/yilian/shouhui/importData'
        }
      }
      state.off.upload = true
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    //导入成功
    function importSuccess() {
      state.page = 1
      getTableData()
    }

    const handleUploadCancel = () => {
      state.off.upload = false
    }

    function settingHandle(type, data) {
      if (type == 1) {
        const title = "删除提示"
        const msg = '您确定要将所选的设备删除吗？'
        state.uniqueId = data.wareGoodsId
        confirmPasswordRef.value.dialogShow(title, msg)
      } else {
        if (state.chooseList.length == 0) {
          return
        }
      }
    }

    const confirmSuccess = () => {
      let json = {
        uniqueId: state.uniqueId
      }
      api.warehouseDelete(json).then(res => {
        successDeal('删除成功！')
        getTableData()
      })
    }

    function selectionChange(list) {
      state.chooseList = list
    }

    // 下载模板
    const exportWarehouseImportTemplate = (data) => {
      const obj = {
        responseType: 'blob',
        wareGoodsId: data.wareGoodsId
      }
      api.warehouseImportTemplate(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    const getShopList = () => {
      api.shopList().then(res => {
        state.shopList1 = JSON.parse(JSON.stringify(res.data.list))
        state.shopList = JSON.parse(JSON.stringify(res.data.list))
        state.shopList.unshift({
          shopId: 'system',
          shopName: '平台',
        })
      })
    }

    const getWarehouseChooseList = () => {
      api.warehouseChooseList().then(res => {
        state.warehouseChooseList = res.data.list
      })
    }

    const strategyAdd = (name, eventStrategyType) => {
      let obj = {
        "deductScore": 0,
        "flowCodeNext": "",
        "flowCodePre": "",
        "flowId": "",
        "processTime": ""
      }
      state[name].push(obj)
    }

    const strategyDelete = (name, index) => {
      state[name].splice(index, 1)
    }

    const dialogCancel = () => {
      state.off.dialogVisible = false
      state.dialogForm = {}
      state.deviceList = [{}]
      dialogFormRef.value.resetFields()
    }

    const dialogSave = () => {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = JSON.parse(JSON.stringify(state.dialogForm))
          json.type = 2 // 操作类别，1-代理商下单，2-管理端手动调拨
          json.children = state.deviceList

          api.transferCreate(json).then(res => {
            successDeal('操作成功！')
            getTableData()
            dialogCancel()
          })
        }
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 280
      setIsDetail()
      getShopList()
      getWarehouseChooseList()
    })

    return {
      ...toRefs(state),
      uploadRef,
      confirmPasswordRef,
      dialogFormRef,
      searchHandle,
      resetHandle,
      lookDetail,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      exportHandle,
      importSuccess,
      importHandle,
      handleUploadCancel,
      settingHandle,
      confirmSuccess,
      selectionChange,
      exportWarehouseImportTemplate,
      strategyAdd,
      strategyDelete,
      dialogCancel,
      dialogSave,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-inventory {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;

      > .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0 15px;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
  .f-strategy-box {
    width: 100%;
    border: 1px solid #d6dee5;
    .f-strategy-header {
      height: 44px;
      background: #d6dee5;
      display: flex;
      align-items: center;
      padding: 0 16px;
    }
    .f-strategy-body {
      li {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        padding: 10px 5px 10px 10px;
      }
    }
  }
  .f-divider {
    width: 100%;
    height: 1px;
    background: #d6dee5;
  }
}
</style>